﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

using Microsoft.Rtc.Collaboration.Samples.HTMLPresenceControls.Controls.Configuration;

namespace Microsoft.Rtc.Collaboration.Samples.HTMLPresenceControls.Controls
{
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:PresenceIndicator runat=server></{0}:PresenceIndicator>")]
    public class PresenceIndicator : WebControl
    {
        bool _showStatus = true;
        bool _showName = true;
        
        /// <summary>
        /// The Sip Address of the contact to display presence for
        /// </summary>
        public string SipAddress { get; set; }

        /// <summary>
        /// Toggle the availability text display mode (e.g. Available, Busy)
        /// </summary>
        public bool ShowStatus
        {
            get { return _showStatus; }
            set { _showStatus = value; }
        }

        /// <summary>
        /// Toggle the contact name display mode
        /// </summary>
        public bool ShowName
        {
            get { return _showName; }
            set { _showName = value; }
        }

        /// <summary>
        /// Render the control
        /// </summary>
        /// <param name="output">HTML control markup</param>
        protected override void RenderContents(HtmlTextWriter output)
        {
            // Config Settings
            int _refreshInterval;
            string _serviceUrl = null;
            
            // Requests to the WCF service get cached - use a guid for cache busting
            string cacheBustingGuid = System.Guid.NewGuid().ToString();

            // Get values from web.config
            try
            {
                var config = (HTMLPresenceControlsConfigurationSection)
                    ConfigurationManager.GetSection("HTMLPresenceControlsConfigurationGroup/HTMLPresenceControlsConfiguration");
                _refreshInterval = config.PresenceServiceSettings.RefreshInterval * 1000; // Convert to milliseconds
                _serviceUrl = config.PresenceServiceSettings.Url.ToString();
            }
            catch (ConfigurationErrorsException) 
            { 
                throw new ConfigurationErrorsException("One or more of the required configuration settings are missing from the web.config file. See documentation for more details."); 
            }
            catch (Exception e) 
            {
                throw e;
            }

            
            //Show everything
            if(ShowName == true && ShowStatus == true)
            {
                output.Write("\n<div class=\"item\" id=\"" + cacheBustingGuid + "\">\n");
                output.Write("<div class=\"name-status-wrapper\">\n");
                output.Write("<span class=\"availability unknown\"></span>\n");
                output.Write("<span class=\"name\"></span>\n");
                output.Write("<span class=\"status\"></span>\n");
                output.Write("</div>\n");
                output.Write("<span class=\"sip\" style=\"display:none;\">" + SipAddress + "</span>\n");
                output.Write("</div>\n");

                // Build the jQuery script block and add it below the control
                string javascript = @"$(function () {$('#" + cacheBustingGuid + "').everyTime(" + _refreshInterval + ", function (i) {$('#" + cacheBustingGuid + "').children().each(function () {var child = $(this);if (child.is('.sip')) {$.ajax({type: 'GET',url: '" + _serviceUrl + "' + child.html()+'&r='+Math.random(),dataType: 'xml',success: function (xmlData) {$(xmlData).find('PresenceSubscription').each(function () {$('#" + cacheBustingGuid + "').find('.availability').removeClass().addClass('availability '+getTicTac($(this).find('Availability').text()));$('#" + cacheBustingGuid + "').find('.status').html($(this).find('Status').text());$('#" + cacheBustingGuid + "').find('.name').html($(this).find('ContactName').text());});},error: function (xhr, ajaxOptions, thrownError) {}});}});});});";
                output.Write("<script type=\"text/javascript\">\n" + javascript + "\n</script>\n");
            }

            // Only show Contact Name
            else if (ShowName == true && ShowStatus == false)
            {
                output.Write("\n<div class=\"item nostatus\" id=\"" + cacheBustingGuid + "\">\n");
                output.Write("<div class=\"name-status-wrapper nostatus\">\n");
                output.Write("<span class=\"availability unknown\"></span>\n");
                output.Write("<span class=\"name\"></span>\n");
                output.Write("</div>\n");
                output.Write("<span class=\"sip\" style=\"display:none;\">" + SipAddress + "</span>\n");
                output.Write("</div>\n");

                //Build the jQuery script block and add it below the control
                string javascript = @"$(function () {$('#" + cacheBustingGuid + "').everyTime(" + _refreshInterval + ", function (i) {$('#" + cacheBustingGuid + "').children().each(function () {var child = $(this);if (child.is('.sip')) {$.ajax({type: 'GET',url: '" + _serviceUrl + "' + child.html()+'&r='+Math.random(),dataType: 'xml',success: function (xmlData) {$(xmlData).find('PresenceSubscription').each(function () {$('#" + cacheBustingGuid + "').find('.availability').removeClass().addClass('availability '+getTicTac($(this).find('Availability').text()));$('#" + cacheBustingGuid + "').find('.name').html($(this).find('ContactName').text());});},error: function (xhr, ajaxOptions, thrownError) {}});}});});});";
                output.Write("<script type=\"text/javascript\">\n" + javascript + "\n</script>\n");
            }

            // Only show Contact Status
            else if (ShowName == false && ShowStatus == true)
            {
                output.Write("\n<div class=\"item noname\" id=\"" + cacheBustingGuid + "\">\n");
                output.Write("<div class=\"name-status-wrapper noname\">\n");
                output.Write("<span class=\"availability unknown\"></span>\n");
                output.Write("<span class=\"status\"></span>\n");
                output.Write("</div>\n");
                output.Write("<span class=\"sip\" style=\"display:none;\">" + SipAddress + "</span>\n");
                output.Write("</div>\n");

                //Build the jQuery script block and add it below the control
                string javascript = @"$(function () {$('#" + cacheBustingGuid + "').everyTime(" + _refreshInterval + ", function (i) {$('#" + cacheBustingGuid + "').children().each(function () {var child = $(this);if (child.is('.sip')) {$.ajax({type: 'GET',url: '" + _serviceUrl + "' + child.html()+'&r='+Math.random(),dataType: 'xml',success: function (xmlData) {$(xmlData).find('PresenceSubscription').each(function () {$('#" + cacheBustingGuid + "').find('.availability').removeClass().addClass('availability '+getTicTac($(this).find('Availability').text()));$('#" + cacheBustingGuid + "').find('.status').html($(this).find('Status').text());});},error: function (xhr, ajaxOptions, thrownError) {}});}});});});";
                output.Write("<script type=\"text/javascript\">\n" + javascript + "\n</script>\n");
            }

            // Only show presence
            else if (ShowName == false && ShowStatus == false)
            {
                output.Write("\n<div class=\"item onlytictac\" id=\"" + cacheBustingGuid + "\">\n");
                output.Write("<div class=\"name-status-wrapper onlytictac\">\n");
                output.Write("<span class=\"availability unknown\"></span>\n");
                output.Write("</div>\n");
                output.Write("<span class=\"sip\" style=\"display:none;\">" + SipAddress + "</span>\n");
                output.Write("</div>\n");

                //Build the jQuery script block and add it below the control
                string javascript = @"$(function () {$('#" + cacheBustingGuid + "').everyTime(" + _refreshInterval + ", function (i) {$('#" + cacheBustingGuid + "').children().each(function () {var child = $(this);if (child.is('.sip')) {$.ajax({type: 'GET',url: '" + _serviceUrl + "' + child.html()+'&r='+Math.random(),dataType: 'xml',success: function (xmlData) {$(xmlData).find('PresenceSubscription').each(function () {$('#" + cacheBustingGuid + "').find('.availability').removeClass().addClass('availability '+getTicTac($(this).find('Availability').text()));});},error: function (xhr, ajaxOptions, thrownError) {}});}});});});";
                output.Write("<script type=\"text/javascript\">\n" + javascript + "\n</script>\n");
            }
        }

        protected override void OnPreRender(EventArgs e) 
        {
            base.OnPreRender(e);

            string jQueryScriptLocation = Page.ClientScript.GetWebResourceUrl(typeof(Microsoft.Rtc.Collaboration.Samples.HTMLPresenceControls.Controls.PresenceIndicator), "Microsoft.Rtc.Collaboration.Samples.HTMLPresenceControls.Controls.Scripts.jquery.timers-1.2.js");
            Page.ClientScript.RegisterClientScriptInclude("Microsoft.Rtc.Collaboration.Samples.HTMLPresenceControls.Controls.Scripts.jquery.timers-1.2.js", jQueryScriptLocation);

            string presenceScriptLocation = Page.ClientScript.GetWebResourceUrl(typeof(Microsoft.Rtc.Collaboration.Samples.HTMLPresenceControls.Controls.PresenceIndicator), "Microsoft.Rtc.Collaboration.Samples.HTMLPresenceControls.Controls.Scripts.presence.styles.js");
            Page.ClientScript.RegisterClientScriptInclude("Microsoft.Rtc.Collaboration.Samples.HTMLPresenceControls.Controls.Scripts.presence.styles.js", presenceScriptLocation);

            string includeTemplate = "<link rel='stylesheet' text='text/css' href='{0}' />";
            string includeLocation = Page.ClientScript.GetWebResourceUrl(this.GetType(), "Microsoft.Rtc.Collaboration.Samples.HTMLPresenceControls.Controls.Styles.PresenceAvailability.css");
            var include = new LiteralControl(String.Format(includeTemplate, includeLocation));

            if (((System.Web.UI.HtmlControls.HtmlHead)Page.Header).Controls.Contains(include) == false)
            {
                ((System.Web.UI.HtmlControls.HtmlHead)Page.Header).Controls.Add(include);
            }
        }
    }
}

